package com.cloudcc.mobile.view.main.fragment;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.bus.StartWebEvent;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.view.dynamic.RelevantActivtiy;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase.OnRefreshListener;
import com.cloudcc.mobile.weight.ui.PullToRefreshWebView;


public class WebFragment extends Fragment {
	private final int OPEN_RESULT = 1;
	private final int PINK_RESULT = 2;
	public static final String ARG_PLANET_NUMBER = "planet_number";
	private PullToRefreshWebView weixinview;
	private ImageView fanhui;
	private ImageView shuaxin;
	private RelativeLayout caozuo;
	private CustomProgressDialog progressDialog;
	private NetWork net;
	private String urlString;
	private SharePreferece share;
	private ValueCallback<Uri> mUploadMessage;
	private String filePath;
	private Uri uri;
	private Context context;
	private LinearLayout network;
	private ImageView menubtn;
	private RelativeLayout webview;
	private View view;
	private WebView weixin;
	/** 显示格式化日期模板 */
	private final static String DATE_FORMAT_STR = "yyyy年MM月dd日 HH:mm";
	private boolean isFrist = true;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		try {
			if (view == null) {
				view = inflater.inflate(R.layout.webview2, null);
				context = getActivity();
				setView(view);
				addListener();
			}
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		} catch (Exception e) {
			Tools.handle(e);
		}
		return view;
	}

	@Override
	public void onResume() {
		if (AppContext.iscomeMenu) {
			AppContext.iscomeMenu = false;
			AppContext.isFirst = true;
			AppContext.isError = false;
			weixin.loadUrl(AppContext.urlString);
		}
		super.onResume();
	}

	private void setView(View view) {
		weixinview = (PullToRefreshWebView) view.findViewById(R.id.weixin);
		weixin = weixinview.getRefreshableView();
		fanhui = (ImageView) view.findViewById(R.id.fanhui);
		shuaxin = (ImageView) view.findViewById(R.id.shuaxin);
		menubtn = (ImageView) view.findViewById(R.id.webview_menubtn);
		caozuo = (RelativeLayout) view.findViewById(R.id.caozuo);
		caozuo.setVisibility(View.GONE);
		webview = (RelativeLayout) view.findViewById(R.id.webview_yemian);
		network = (LinearLayout) view.findViewById(R.id.network_bad);
		share = new SharePreferece(context);
		caozuo.setVisibility(View.GONE);
		weixin.setVisibility(View.GONE);
		progressDialog = CustomProgressDialog.createDialog(context);
		webview();
		setLastUpdateTime();
	}

	/**
	 * webview操作类
	 */
	@SuppressLint("SetJavaScriptEnabled")
	public void webview() {
		weixin.requestFocus();
		weixin.setLayerType(View.LAYER_TYPE_SOFTWARE, null);// 防止滑动的时候闪屏
		weixin.loadUrl(AppContext.urlString);
		weixin.reload();
		WebSettings webstting = weixin.getSettings();
		webstting.setJavaScriptEnabled(true);
		webstting.setAllowFileAccess(true);
		webstting.setSupportZoom(true);
		webstting.setJavaScriptCanOpenWindowsAutomatically(true);
		webstting.setCacheMode(WebSettings.LOAD_NO_CACHE);// 是否缓存
		weixin.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				if (url.equals(AppContext.indexUrl)) {
					EventEngine.post(new MenuToggleEvent(false,false));
					weixin.stopLoading();
					return;
				}
				urlString = url;
				handler.sendEmptyMessage(1);
				if (url.equals(UrlTools.loginurl)) {
					Intent intent = new Intent(UrlTools.loginurl);
					context.sendBroadcast(intent);
				}
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// 加载完了再调用js登录代码
				handler.sendEmptyMessage(2);
				setLastUpdateTime();// 刷新时间
				if (AppContext.isError) {
					weixin.setVisibility(View.GONE);
					caozuo.setVisibility(View.GONE);
					network.setVisibility(View.VISIBLE);
					if (!AppContext.isFirst) {
						AppContext.isError = false;
					}
					AppContext.isFirst = false;
				} else {
					AppContext.isFirst = true;
					weixin.setVisibility(View.VISIBLE);
					caozuo.setVisibility(View.GONE);
					network.setVisibility(View.GONE);
				}
				super.onPageFinished(view, url);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				
				LogUtils.d("webview", "跳转：" + url);
				if (UrlManager.isWapLogin(url)) {// 跳转去登录
					EventEngine.register(WebFragment.this);
					Intent intent = new Intent(getActivity(), BindActivity.class);
					getActivity().startActivity(intent);
					return true;
				}
				
				if (url.contains("/wx_taskquery.action?m=query&id=")) {
					String id = url.substring(
							Tools.getCharacterPosition(url, "=", 2) + 1,
							Tools.getCharacterPosition(url, "&", 2));
					Intent intent = new Intent(getActivity(),
							RelevantActivtiy.class);
					intent.putExtra("web", id);
					intent.putExtra("web.url", UrlManager.APP_UR+ UrlTools.getObjectUrl(id));
					//AppContext.urlString =UrlManager.APP_UR+ UrlTools.getObjectUrl(id) ;
					startActivity(intent);
					return true;
				} else if (url.contains("/weiquery.action?m=query&id=")) {
					String id = url.substring(
							Tools.getCharacterPosition(url, "=", 2) + 1,
							url.length());
					Tools.i("followService", id);
					Intent intent = new Intent(getActivity(),
							RelevantActivtiy.class);
					intent.putExtra("web", id);
					intent.putExtra("web.url",UrlManager.APP_UR+ UrlTools.getObjectUrl(id));
					//AppContext.urlString = UrlTools.weixinUrl
						//	+ UrlTools.getObjectUrl(id);
					Tools.i("followService", AppContext.urlString);
					startActivity(intent);
					return true;
				} else if (url.contains("/weiquery.action?id=")) {
					// http://test.cloudcc.cn/weiquery.action?m=query&id=b11201400002321255TY
					// http://test.cloudcc.cn/weiquery.action?id=b11201400002321255TY&m=query
					// [a-zA-Z_0-9]{20} 20位 字符和数组混搭
					String type = url.substring(
							Tools.getCharacterPosition(url, "=", 2) + 1,
							url.length());
					Tools.i("followService", type);
					if (type.equals("query")) {
						String id = url.substring(
								Tools.getCharacterPosition(url, "=", 1) + 1,
								url.length() - 8);
						Tools.i("followService", id);
						Intent intent = new Intent(getActivity(),
								RelevantActivtiy.class);
						intent.putExtra("web", id);
						intent.putExtra("web.url",UrlManager.APP_UR+UrlTools.getObjectUrl(id));
						//AppContext.urlString = UrlTools.weixinUrl
						//		+UrlTools.getObjectUrl(id) ;
						Tools.i("followService", AppContext.urlString);
						startActivity(intent);
						return true;
					} else {

					}

				}
				if (url.equals(UrlTools.weixinUrl + "/WeiXin_index.action")) {
					Intent intent = new Intent(AppContext.WEB_TO_MENU);
					getActivity().sendBroadcast(intent);
					return true;
				} else {
					// 自身加载新链接,不做外部跳转
					view.loadUrl(url);
					return true;
				}
			}

			public void onReceivedSslError(WebView view,
					android.webkit.SslErrorHandler handler,
					android.net.http.SslError error) {
				handler.proceed();
			};

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				AppContext.isError = true;
				return;
			}
		});
		weixin.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				return true;
			}

			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				DialogUtils dialogutils = new DialogUtils(context);
				dialogutils.showUpdateDialog(context, "网页提示", message);
				dialogutils.setOnDoClicktListener(new OnDoClickListener() {
					@Override
					public void confirm() {
						result.confirm();
					}

					@Override
					public void cancel() {
						result.cancel();
					}
				});
				return true;
			}

			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType) {
				if (mUploadMessage != null)
					return;
				mUploadMessage = uploadMsg;
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				i.setType("*/*");
				startActivityForResult(Intent.createChooser(i, "选择文件"),
						PINK_RESULT);
			}

			// For Android > 4.1.1
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType, String capture) {
				openFileChooser(uploadMsg, acceptType);
			}

			// For Android < 3.0
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				openFileChooser(uploadMsg, "");
			}
			
			
		});
	}
	public void onEventMainThread(StartWebEvent event) {
		if (event.isError()) {
			EventEngine.post(new MenuToggleEvent(false, false));
			return;
		}
		weixin.loadUrl(AppContext.urlString);
		EventEngine.uregister(this);
	}
	protected void setLastUpdateTime() {
		weixinview.setLastUpdatedLabel(new SimpleDateFormat(DATE_FORMAT_STR,
				Locale.CHINA).format(new Date()));
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				startProgressDialog();
				break;
			case 2:
				stopProgressDialog();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@SuppressLint("SdCardPath")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == PINK_RESULT) {
			if (null == mUploadMessage)
				return;
			Uri result = intent == null
					|| resultCode != getActivity().RESULT_OK ? null : intent
					.getData();
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		}
	}

	/**
	 * dialog开始显示
	 */
	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(context);
			progressDialog.setCancelable(true);
			progressDialog.setCanceledOnTouchOutside(false);
			// progressDialog.setMessage("正在加载中...");
		}
		progressDialog.show();
	}

	/**
	 * 停止dialog
	 */
	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/**
	 * 监听 mWebView.goBack(); //后退 mWebView.goForward();//前进 mWebView.reload();
	 * //刷新
	 */
	private void addListener() {
		weixinview.setOnRefreshListener(new OnRefreshListener<WebView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<WebView> refreshView) {
				weixin.reload();
				weixinview.onPullDownRefreshComplete();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<WebView> refreshView) {
			}
		});
		network.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				weixin.reload(); // 刷新
				//AppContext.isFirst = true;
				//AppContext.isError = false;
			}
		});
		menubtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//AppContext.menu.toggle();
			}
		});
		fanhui.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (urlString.equals(UrlTools.weixinUrl + UrlTools.menuurl)) {
					weixin.reload(); // 刷新
				} else {
					weixin.goBack(); // 后退
				}
			}
		});
		shuaxin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				weixin.reload(); // 刷新
			}
		});

	}
}